// 查询设备
$(function () {
  if(/mobile/i.test(navigator.userAgent)) {
    $('.right-wrap').remove();
    $('.main-wrap').css({'width': '100%','padding':'0 20px'});
  }
});

//模拟登录退出
$(function() {
  $('.login-submit').on('click', function(e) {
    var user = $('input[name=username]').val();
    var pass = $('input[name=password]').val();

    if (user == 'admin' && pass == '666666') {
      // 登录成功
      window.location.href = '/index-login.html';

    } else {
      // 登录失败
      $('.login-error').text('请使用admin/666666登录测试');
    }
    return false;
  });

  $('.login-wrap').on('click', '.exit', function() {
    window.location.href = '/index.html';
  });
});

// 首页导航排版
$(function() {
  var aTopNav = $('.topnav-sort');
  for (var i = 0; i < aTopNav.length; i++) {
    if (i % 5 == 4) {
      aTopNav.eq(i).css({
        'text-align': 'right',
        'width': '180px',
        'margin-left': '15px',
      });
    }
    if (i % 5 == 1 || i % 5 == 2 || i % 5 == 3) {
      aTopNav.eq(i).css({
        'margin-left': '35px',
        'width': '220px'
      });
    }
  }
});

// 图片排版
// $(function() {
//   if ($('.img-trumb img')) {
//     $('.img-trumb img').each(function(index) {
//       var height = $(this).height();
//       $(this).css({
//         'margin-top': -height / 2
//       });
//       $(this).load(function() {
//         var height = $(this).height();
//         $(this).css({
//           'margin-top': -height / 2
//         });
//
//       });
//     });
//     $('.img-trumb').each(function(index) {
//       if ((index - 1) % 3 == 0) {
//         $(this).css({
//           'margin': '0 38px'
//         });
//       }
//     });
//   }
// });

// 点赞
var alreadyZan = false;
$(function() {
  // 根据点赞的状态来判断样式
  if (alreadyZan) {
    $('.article-metal a').addClass('zaned');
  } else {
    $('.article-metal a').removeClass('zaned');
  }


  $('.article-metal a').on('click', function(event) {
    // 取点赞数
    var num = $('.article-metal a').text().match(/\d+/g)[0];
    // console.log(num);
    if (alreadyZan) {
      // 已经点赞，点击 num -1
      $('.article-metal a').text('点赞(' + (--num) + ')');
      textSlideUpFade('- 1', '.article-metal a', event);
    } else {
      // 未点赞，点击
      $('.article-metal a').text('点赞(' + (++num) + ')');
      textSlideUpFade('+ 1', '.article-metal a', event);
    }
    $('.article-metal a').toggleClass('zaned');
    alreadyZan = !alreadyZan;
    // 将num发给服务器
    // function(){...}
  });
});

// 文字向上移动消失函数
function textSlideUpFade(text, parent, event) {
  var floatNum = $('<div>' + text + '</div>');
  floatNum.css({
    'position': 'fixed',
    'left': event.clientX + 'px',
    'top': event.clientY + 'px',
    'font-size': '18px',
    'font-weight': 'bold',
    'z-index': 9999
  });
  $(parent).append(floatNum);
  var t = event.clientY;
  var final_t = event.clientY - 50;
  setInterval(function() {
    if (t > final_t) {
      t--;
      floatNum.css('top', t + 'px');
    } else {
      floatNum.remove();
    }
  }, 10);
}

// login
$(function() {
  // 鼠标移入登录按钮
  $('.login-wrap').on('mouseenter', '.btn-login', function() {
    $('.usernamelogin').addClass('focus');
    $('.codelogin').removeClass('focus');
    $('.usernamelogin-body').css('display', 'block');
    $('.codelogin-body').css('display', 'none');
    $('.login-window').stop(true, true).fadeIn(200);
    $('.login-error').html('');
  });
  $('.login-wrap').on('click', '.btn-login', function(e) {
    $('.login-window').stop(true, true).fadeToggle(200);
    e.stopPropagation();
  });
  // 鼠标点击页面
  $(document).on('click', function(e) {
    $('.login-window').stop(true, true).fadeOut(200);
  });
  $('.login-window').on('click', function(e) {
    e.stopPropagation();
  });
  // 鼠标移出登录窗口
  // $('.login-window').on('mouseleave', function(){
  //   $(this).stop(true, true).fadeOut(200);
  // });
  //  页面滚动
  $(document).on('scroll', function() {
    $('.login-window').stop(true, true).fadeOut(200);
  });
  // 登录切换
  $('.codelogin').on('click', function() {
    $(this).addClass('focus');
    $('.usernamelogin').removeClass('focus');
    $('.codelogin-body').css('display', 'block');
    $('.usernamelogin-body').css('display', 'none');
    if (global_ajax_run) return false;
    $.ajax({
      url: '/virtualdatas/login-erweima.json',
      dataType: 'json',
      beforeSend: function() {
        $('.codelogin-erweima').html('');
        ajaxBeforeSend($('.codelogin-erweima'));
      },
      complete: function() {
        ajaxCompleted($('.codelogin-erweima'));
      },
      success: function(json) {
        $('.codelogin-erweima').html('<img src="' + json.src + '" alt="扫码登录">');
      },
      error: function(err) {
        $('.codelogin-erweima').append('<div style="font-size:10px;text-align:center">数据加载失败</div>');
        console.log('扫码二维码调入失败');
      }

    });
  });
  $('.usernamelogin').on('click', function() {
    $(this).addClass('focus');
    $('.codelogin').removeClass('focus');
    $('.usernamelogin-body').css('display', 'block');
    $('.codelogin-body').css('display', 'none');
  });
});

// 登录后菜单
$(function() {
  $('.login-wrap').on('mouseenter', '.statusin-username', function() {
    $('.statusin-window').stop(true, true).slideDown(200);
  });
  $('.login-wrap').on('click', '.statusin-username', function(e) {
    $('.statusin-window').stop(true, true).slideToggle(200);
    e.stopPropagation();
  });

  $(document).on('scroll', function() {
    $('.statusin-window').stop(true, true).slideUp(300);
  });
  $('.statusin-window').on('mouseleave', function() {
    $(this).stop(true, true).slideUp(300);
  });
  // 鼠标点击页面
  $(document).on('click', function(e) {
    $('.statusin-window').stop(true, true).slideUp(300);
  });
  $('.statusin-window').on('click', function(e) {
    e.stopPropagation();
  });
});

// 微信公众号按钮
$(function() {
  $('.btn-weixin').on('mouseenter', function() {
    $('.weixin-window').stop(true, true).slideDown(200);
  });
  $('.btn-weixin').on('mouseleave', function() {
    $('.weixin-window').stop(true, true).slideUp(200);
  });
});

// 网站地图按钮
$(function() {
  $('.btn-sitemap').on('mouseenter', function(e) {
    $('.sitemap-window').stop(true, true).slideDown(300);
    e.stopPropagation();
  });
  $('.btn-sitemap').on('click', function(e) {
    $('.sitemap-window').stop(true, true).slideToggle(300);
    e.stopPropagation();
  });
  $(document).on('scroll', function() {
    $('.sitemap-window').stop(true, true).slideUp(300);
  });
  $('.sitemap-window').on('mouseleave', function() {
    $(this).stop(true, true).slideUp(300);
  });
  // 鼠标点击页面
  $(document).on('click', function(e) {
    $('.sitemap-window').stop(true, true).slideUp(300);
  });
  $('.sitemap-window').on('click', function(e) {
    e.stopPropagation();
  });
});

// 阅读排行榜
$(function() {
  if ($('.read-rank').length == 0) return false;
  var dev = true;
  if (dev) {
    $.ajax({
      url: 'virtualdatas/rank.json',
      dataType: 'json',
      success: function(content) {
        var oParent = $('.read-rank');
        for (var i = 0; i < 15; i++) {
          var ele = $('<div class="rank-body"><div class="rank-num">' + (i + 1 > 9 ? i + 1 : '0' + (i + 1)) + '</div><div class="rank-title"><a href="?ID=' + content[i].ID + '">' + content[i].title.slice(0, 32) + '</a></div><div class="rank-count">' + content[i].readCount + '</div></div>');
          oParent.append(ele);
        }
      },
      error: function(err) {
        console.log(err);
      }
    })
  } else {
    // 正式环境
    GetContentsJSON('系统:热借图书', 0, 0, function(json) {
      var n = json.indexOf('[');
      var str = json.substring(n);
      var content = JSON.parse(str);

      var oParent = $('.read-rank');
      for (var i = 0; i < 15; i++) {
        var ele = $('<div class="rank-body"><div class="rank-num">' + (i + 1 > 9 ? i + 1 : '0' + (i + 1)) + '</div><div class="rank-title"><a href="?ID=' + content[i].ID + '">' + content[i].title.slice(0, 32) + '</a></div><div class="rank-count">' + content[i].readCount + '</div></div>');
        oParent.append(ele);
      }
    });
  }
});

// 推荐图书swiper模块
$(function() {
  if ($('.swiper-container2').length == 0) return false;
  var dev = true;
  if (dev) {
    $.ajax({
      url: 'virtualdatas/recommendebooks.json',
      dataType: 'json',
      success: function(content) {
        var arr1 = content.splice(0, 6);
        var arr2 = content.splice(0, 6);
        var arr3 = content.splice(0, 6);
        var data = [];
        data.push(arr1);
        data.push(arr2);
        data.push(arr3);

        var oParent = $('.swiper-container2 .swiper-wrapper')
        for (var i = 0; i < data.length; i++) {
          var slide = $('<div class="swiper-slide"></div>');
          var frame = $('<div class="recommendedbooks-frame"></div>');
          slide.append(frame);

          for (var j = 0; j < data[i].length; j++) {
            var json = data[i][j];
            var ele = $('<a class="recommendedbooks-item" href="javascript:;"><span class="img"><img src="' + json.imghref + '" alt="book"></span><span class="title">' + json.title + '</span><span class="writer">' + json.author + '</span><span class="sort">' + json.sort + '</span><span class="publisher">' + json.publisher + '</span></a>');

            frame.append(ele);
          }

          oParent.append(slide);
        }
        // 开始 swiper
        var mySwiper = $('.swiper-container2').swiper({
          loop: true,
          mode: 'vertical',
          autoplay: 10000,
          autoplayDisableOnInteraction: false,
          // visibilityFullFit : true,
          pagination: '.swiper-p2',
          paginationClickable: true,
          grabCursor: true,
          //其他设置
        });
      },
      error: function(err) {
        console.log(err);
      }
    });
  } else {
    GetContentsJSON('系统:推荐图书', 0, 0, function(json) {
      var n = json.indexOf('[');
      var str = json.substring(n);
      var content = JSON.parse(str);

      // console.log(content.length);

      var arr1 = content.splice(0, 6);
      var arr2 = content.splice(0, 6);
      var arr3 = content.splice(0, 6);
      var data = [];
      data.push(arr1);
      data.push(arr2);
      data.push(arr3);

      var oParent = $('.swiper-container2 .swiper-wrapper')
      for (var i = 0; i < data.length; i++) {
        var slide = $('<div class="swiper-slide"></div>');
        var frame = $('<div class="recommendedbooks-frame"></div>');
        slide.append(frame);

        for (var j = 0; j < data[i].length; j++) {
          var json = data[i][j];
          var ele = $('<a class="recommendedbooks-item" href="javascript:;"><span class="img"><img src="' + json.imghref + '" alt="book"></span><span class="title">' + json.title + '</span><span class="writer">' + json.author + '</span><span class="sort">' + json.sort + '</span><span class="publisher">' + json.publisher + '</span></a>');

          frame.append(ele);
        }

        oParent.append(slide);
      }
      // 开始 swiper
      var mySwiper = $('.swiper-container2').swiper({
        loop: true,
        mode: 'vertical',
        autoplay: 10000,
        autoplayDisableOnInteraction: false,
        // visibilityFullFit : true,
        pagination: '.swiper-p2',
        paginationClickable: true,
        grabCursor: true,
        //其他设置
      });
    });
  }
});

// 首页左上角头条swiper模块
$(function() {
  if ($('.swiper-container1').length == 0) return false;
  var dev = true;
  if (dev) {
    // 开发模式
    $.ajax({
      url: 'virtualdatas/toutiao.json',
      dataType: 'json',
      success: function(content) {
        // 插入元素
        var oParent = $('.swiper-container1 .swiper-wrapper');
        for (var i = 0; i < content.length; i++) {
          var ele = $('<div class="swiper-slide"><a href="article.html?ID=' + content[i].ID + '"><div class="figure"><img src="' + content[i].imghref + '" alt="示例图片"></div><span class="figcaption">' + content[i].describe.slice(0, 54) + '</span></a></div>');

          oParent.append(ele);
        }

        // 调用swiper
        var mySwiper = $('.swiper-container1').swiper({
          loop: true,
          autoplay: 5000,
          autoplayDisableOnInteraction: false,
          // visibilityFullFit : true,
          pagination: '.swiper-p1',
          paginationClickable: true,
          grabCursor: true,
          //其他设置
        });
      },
      error: function(err) {
        console.log(err);
      }
    });
  } else {
    // 正式环境
    GetContentsJSON('系统:头条新闻', 0, 0, function(json) {
      var n = json.indexOf('[');
      var str = json.substring(n);
      var content = JSON.parse(str);

      // 插入元素
      var oParent = $('.swiper-container1 .swiper-wrapper');
      for (var i = 0; i < content.length; i++) {
        var ele = $('<div class="swiper-slide"><a href="article.html?ID=' + content[i].ID + '"><div class="figure"><img src="' + content[i].imghref + '" alt="示例图片"></div><span class="figcaption">' + content[i].describe.slice(0, 54) + '</span></a></div>');

        oParent.append(ele);
      }

      // 调用swiper
      var mySwiper = $('.swiper-container1').swiper({
        loop: true,
        autoplay: 5000,
        autoplayDisableOnInteraction: false,
        // visibilityFullFit : true,
        pagination: '.swiper-p1',
        paginationClickable: true,
        grabCursor: true,
        //其他设置
      });
    });
  }



  // 左右箭头
  // $('.arrow-left').on('click', function(e) {
  //   e.preventDefault();
  //   mySwiper.swipePrev();
  // });
  // $('.arrow-right').on('click', function(e) {
  //   e.preventDefault();
  //   mySwiper.swipeNext();
  // });
});

// 回到顶部
$(function() {
  $('.backtotop').on('click', function() {
    $('html,body').stop(true).animate({
      'scrollTop': 0
    }, 300);

    return false;
  });
});

// tab切换
$(function() {
  // // 新闻
  // tabSwitch($('#news'), [function() {
  //   loadDatas('news1.json', 5, $('#news'));
  //   loadDatas('news1.json', 5, $('#news'));
  //   loadDatas('news2.json', 8, $('#news'));
  //   loadDatas('news3.json', 12, $('#news'));
  // }, function() {
  //   loadDatas('activity.json', 20, $('#news'));
  //   loadDatas('resources.json', 15, $('#news'));
  //   loadDatas('technology.json', 8, $('#news'));
  // }, function() {
  //   loadDatas('technology.json', 8, $('#news'));
  //   loadDatas('activity.json', 20, $('#news'));
  //   loadDatas('resources.json', 15, $('#news'));
  // }]);
  //
  // // 活动
  // tabSwitch($('#activity'), [function() {
  //   loadDatas('resources.json', 8, $('#activity'));
  // }, function() {
  //   loadDatas('activity.json', 8, $('#activity'));
  // }, function() {
  //   loadDatas('technology.json', 8, $('#activity'));
  // }]);
  //
  // // 科技
  // tabSwitch($('#technology'), [function() {
  //   loadDatas('resources.json', 8, $('#technology'));
  // }, function() {
  //   loadDatas('activity.json', 8, $('#technology'));
  // }, function() {
  //   loadDatas('technology.json', 8, $('#technology'));
  // }]);
  //
  // // 资源
  // tabSwitch($('#resources'), [function() {
  //   loadDatas('resources.json', 8, $('#resources'));
  // }, function() {
  //   loadDatas('activity.json', 8, $('#resources'));
  // }, function() {
  //   loadDatas('technology.json', 8, $('#resources'));
  // }]);


  // 新闻
  tabSwitch($('#news'), [function() {
    requestData('#news', 18, '目录:公告文章');
    requestData('#news', 8, '目录:政策文件');
    requestData('#news', 6, '目录:公司动态');
  }, function() {
    requestData('#news', 18, '目录:资讯');
  }, function() {
    requestData('#news', 28, '目录:动态');
  }]);

  // 活动
  tabSwitch($('#activity'), [function() {
    requestData('#activity', 8, '目录:活动');
  }, function() {
    requestData('#activity', 8, '目录:专栏');
  }, function() {
    requestData('#activity', 8, '目录:公益');
  }]);

  // 科技
  tabSwitch($('#technology'), [function() {
    requestData('#technology', 8, '目录:科技');
  }, function() {
    requestData('#technology', 8, '目录:系统');
  }, function() {
    requestData('#technology', 8, '目录:硬件');
  }]);

  // 资源
  tabSwitch($('#resources'), [function() {
    requestData('#resources', 8, '目录:资源');
  }, function() {
    requestData('#resources', 8, '目录:视频');
  }, function() {
    requestData('#resources', 8, '目录:讲座');
  }]);
});

// tab切换函数
// tabSwitch(最外层元素,tab对应的行数数组)
function tabSwitch(ele, arr) {
  ele.find('.nav-list').each(function(index) {
    var tabBody = $(this).parents('.tab').find('.tab-body');
    $(this).on('mouseenter', function() {
      // 如果是当前tab,则退出
      if ($(this).hasClass('active')) return false;
      // 如果存在其他ajax函数,则退出
      if (global_ajax_run) return false;
      ele.find('.nav-list').each(function() {
        $(this).removeClass('active');
      });
      $(this).addClass('active');
      tabBody.empty();

      for (var i = 0; i < arr.length; i++) {
        if (i == index) {
          // 执行对应的数据调取函数
          arr[i]();
        }
      }
    });
  });
}

// ajax加载数据 替换为服务端渲染
$(function() {
  var dev = true;
  if (dev) {
    // 新闻
    requestData('#news', 18, '目录:公告文章');
    requestData('#news', 8, '目录:政策文件');
    requestData('#news', 6, '目录:公司动态');

    // 活动
    requestData('#activity', 8, '目录:相关活动');

    // 科技
    requestData('#technology', 8, '目录:科技');

    // 资源
    requestData('#resources', 8, '目录:系统使用视频');

    // 链接区
    requestData('#linkarea', 8, '目录:常见问题解答');
  }
});

// 加载动画加载数据封装
function requestData(ele, count, url) {
  var dev = true;
  count = count || 0;
  ajaxBeforeSend(ele);
  if (dev) {
    // 开发环境
    GetContentsJSON(function(json) {
      appendTitle(ele, count, json);
    });

    function GetContentsJSON(fn) {
      $.ajax({
        url: 'virtualdatas/testnews.json',
        dataType: 'json',
        success: function(data) {
          fn(data);
        },
        error: function(err) {
          console.log(err);
        }
      })
    }
  } else {
    // 服务器环境
    window.GetContentsJSON(url, 0, count, function(json) {
      var n = json.indexOf('{');
      var str = json.substring(n);
      var json2 = JSON.parse(str);

      appendTitle(ele, count, json2);
    });
  }
}

// GetContentsJSON('目录:公告文章', 0, 0, function

// ajaxBeforeSend
// ajaxCompleted
// 插入请求结果
function appendTitle(ele, count, json) {
  var $ul = $('<ul class="arc-title showInBottom a-time003"></ul>');
  if (json.article.length == 0) {
    // 没有文章
    $ul.html('<li style="color: red;text-align:center;">没有文章！</li>');
    $(ele).find('.tab-body').append($ul);
    ajaxCompleted(ele);
    return false;
  }
  for (var i = 0; i < count; i++) {
    if (json.article[i]) {
      if (i == 0) {
        var $li = $('<li class="arc-title first"><a href="article.html?ID=' + json.article[i].ID + '">' + json.article[i].Title + '</a></li>');

        $ul.append($li);
      } else {
        var $li = $('<li class="arc-title"><a href="article.html?ID=' + json.article[i].ID + '">' + json.article[i].Title + '</a></li>');

        $ul.append($li);
      }
    }
  }
  $(ele).find('.tab-body').append($ul);
  ajaxCompleted(ele);
}

//ajax请求状态锁
var global_ajax_run = false;
// ajax 加载数据函数
// loadDatas(文件名称, 调入条数, 最外层元素)
function loadDatas(filename, count, ele) {
  ele = ele.find('.tab-body');
  $.ajax({
    url: '/virtualdatas/' + filename,
    dataType: 'json',
    beforeSend: function() {
      ajaxBeforeSend(ele);
    },
    complete: function() {
      ajaxCompleted(ele);
    },
    success: function(json) {
      var $ul = $('<ul class="arc-title showInBottom a-time003"></ul>');
      for (var i = 0; i < count; i++) {
        if (json.article[i]) {
          if (i == 0) {
            var $li = $('<li class="arc-title first"><a href="/' + json.article[i].id + '">' + json.article[i].title + '</a></li>');

            $ul.append($li);
          } else {
            var $li = $('<li class="arc-title"><a href="/' + json.article[i].id + '">' + json.article[i].title + '</a></li>');

            $ul.append($li);
          }
        }
      }
      ele.append($ul);
    },
    error: function(err) {
      // console.log('数据读取失败');
      ele.append('<div style="font-size:10px;text-align:center">数据加载失败</div>');
      console.log(err.responseText);
      global_ajax_run = false;
    }
  });
}

// ajax发送前loading函数
function ajaxBeforeSend(ele) {
  var $loading = '<div class="loading"><i class="loading-img"></i>数据加载中...</div>';
  $(ele).append($loading);

  global_ajax_run = true;
}

// ajax请求完成函数
function ajaxCompleted(ele) {
  $(ele).find('.loading').remove(); //删除loading
  // 插入li
  global_ajax_run = false;
}

// GetContentsJSON('目录:公告文章', 0, 0, function(contents) {
//   console.log(contents);
// });

// 目录清单列表
$(function() {
  // console.log(window.location);
  if (window.location.href.indexOf('article_list') != -1) {
    var href = window.location.href.split('?')[1].split('&')[0].split('=')[1];

    switch (href) {
      case 'news1':
        console.log('新闻');
        requestArticleIndex(12, '目录:' + '公告文章');

        var oTarget = $('.breadcrumb');
        var ele = $('<a href="index.html">门户首页</a> > <span>新闻</span>');
        oTarget.append(ele);

        break;
      case 'news2':
        console.log('资讯');
        requestArticleIndex(12, '目录:' + '政策文件');

        var oTarget = $('.breadcrumb');
        var ele = $('<a href="index.html">门户首页</a> > <span>资讯</span>');
        oTarget.append(ele);

        break;
      case 'news3':
        console.log('动态');
        requestArticleIndex(12, '目录:' + '公司动态');

        var oTarget = $('.breadcrumb');
        var ele = $('<a href="index.html">门户首页</a> > <span>动态</span>');
        oTarget.append(ele);

        break;

      case 'act1':
        console.log('活动');
        requestArticleIndex(12, '目录:' + '活动');

        var oTarget = $('.breadcrumb');
        var ele = $('<a href="index.html">门户首页</a> > <span>活动</span>');
        oTarget.append(ele);
        break;
      case 'act2':
        console.log('专栏');
        requestArticleIndex(12, '目录:' + '专栏');

        var oTarget = $('.breadcrumb');
        var ele = $('<a href="index.html">门户首页</a> > <span>专栏</span>');
        oTarget.append(ele);
        break;
      case 'act3':
        console.log('公益');
        requestArticleIndex(12, '目录:' + '公益');

        var oTarget = $('.breadcrumb');
        var ele = $('<a href="index.html">门户首页</a> > <span>公益</span>');
        oTarget.append(ele);
        break;

      case 'tech1':
        console.log('科技');
        requestArticleIndex(12, '目录:' + '科技');

        var oTarget = $('.breadcrumb');
        var ele = $('<a href="index.html">门户首页</a> > <span>科技</span>');
        oTarget.append(ele);
        break;
      case 'tech2':
        console.log('系统');
        requestArticleIndex(12, '目录:' + '系统');

        var oTarget = $('.breadcrumb');
        var ele = $('<a href="index.html">门户首页</a> > <span>系统</span>');
        oTarget.append(ele);
        break;
      case 'tech3':
        console.log('硬件');
        requestArticleIndex(12, '目录:' + '硬件');

        var oTarget = $('.breadcrumb');
        var ele = $('<a href="index.html">门户首页</a> > <span>硬件</span>');
        oTarget.append(ele);
        break;

      case 'res1':
        console.log('资源');
        requestArticleIndex(12, '目录:' + '资源');

        var oTarget = $('.breadcrumb');
        var ele = $('<a href="index.html">门户首页</a> > <span>资源</span>');
        oTarget.append(ele);
        break;
      case 'res2':
        console.log('视频');
        requestArticleIndex(12, '目录:' + '视频');

        var oTarget = $('.breadcrumb');
        var ele = $('<a href="index.html">门户首页</a> > <span>视频</span>');
        oTarget.append(ele);
        break;
      case 'res3':
        console.log('讲座');
        requestArticleIndex(12, '目录:' + '讲座');

        var oTarget = $('.breadcrumb');
        var ele = $('<a href="index.html">门户首页</a> > <span>讲座</span>');
        oTarget.append(ele);
        break;

      case 'pic1':
        console.log('图片展示区');
        requestArticleIndex(12, '目录:' + '图片展示区');

        var oTarget = $('.breadcrumb');
        var ele = $('<a href="index.html">门户首页</a> > <span>图片展示区</span>');
        oTarget.append(ele);
        break;
      case 'link1':
        console.log('链接区');
        requestArticleIndex(12, '目录:' + '链接区');

        var oTarget = $('.breadcrumb');
        var ele = $('<a href="index.html">门户首页</a> > <span>链接区</span>');
        oTarget.append(ele);
        break;

      default:
        break;
    }

    // case '资源':
    //   return url + 'res1';
    // case '视频':
    //   return url + 'res2';
    // case '讲座':
    //   return url + 'res3';
    //
    // case '图片展示区':
    //   return url + 'pic1';
    // case '链接区':
    //   return url + 'link1';
  }
});

// 修改面包削导航
function breadcrumbSet() {}

// 加载目录
function requestArticleIndex(count, url) {
  var dev = true;
  count = count || 0;
  if (dev) {
    // 开发环境
    GetContentsJSON(function(json) {
      appendAIndex(count, json);
    });

    function GetContentsJSON(fn) {
      $.ajax({
        url: 'virtualdatas/testnews.json',
        dataType: 'json',
        success: function(data) {
          fn(data);
        },
        error: function(err) {
          console.log(err);
        }
      })
    }
  } else {
    // 服务器环境
    window.GetContentsJSON(url, 0, count, function(json) {
      // 兼容ie8
      var n = json.indexOf('{');
      var str = json.substring(n);
      var json2 = JSON.parse(str);

      appendAIndex(count, json2);
    });
  }
}

function appendAIndex(count, json) {
  var oTarget = $('.article-l');
  if (json.article.length == 0) {
    // 没有目录做处理
    oTarget.html('<li style="color:red;font-weight:bold;">该目录下无文章!</li>');
    return false;
  }
  count = (count <= json.article.length) ? count : json.article.length;
  for (var i = 0; i < count; i++) {
    var ele = $('<li class="article-l-item"><div class="item-left"><a href="article.html?ID=' + json.article[i].ID + '">' + json.article[i].Title + '</a></div><div class="item-right"><span class="article-date">' + json.article[i].Date + '</span></div></li>');
    oTarget.append(ele);
  }

  // 每5个间隔一下
  $('.article-l-item').each(function(index) {
    if ((index + 1) % 5 == 0) {
      $(this).css({
        'margin-bottom': '10px',
        'border-bottom': '1px solid #efefef',
        'padding-bottom': '10px'
      })
    }
  });
}

// 文章
$(function() {
  if (window.location.href.indexOf('article.html') != -1) {
    // var articleID = window.location.href.split('?')[1].split('=')[1];
    var articleID = window.location.href.split('?')[1].split('&')[0].split('=')[1];
    console.log(articleID);
    requestArticleDetail(articleID);
  }
});


// GetContentsJSON('1927', 0, 0, function (contents) {$('#contentlist').html(contents);})

// 加载文章
function requestArticleDetail(url) {
  var dev = true;
  if (dev) {
    // 开发环境
    GetContentsJSON(function(json) {
      appendArticle(json);
    });

    function GetContentsJSON(fn) {
      $.ajax({
        url: 'virtualdatas/articledetail.json',
        dataType: 'json',
        success: function(data) {
          fn(data);
        },
        error: function(err) {
          console.log(err);
        }
      })
    }
  } else {
    // 服务器环境
    window.GetContentsJSON(url, 0, 0, function(json) {
      if (!json) {
        $('.article-body').html('<p style="color:red;font-weight:bold;">没有找到文章！<a href="index.html">返回首页</a></p>')
      }
      // 兼容ie8
      var n = json.indexOf('{');
      var str = json.substring(n);
      var json2 = JSON.parse(str);

      appendArticle(json2);
    });
  }
}

function appendArticle(json) {
  // 面包削
  var oTarget = $('.breadcrumb-p');
  var ele = $('<div class="breadcrumb"><a href="index.html">门户首页</a> > <a href="' + findListUrl(json.catalog) + '">' + json.catalog + '</a> > 正文</div>');
  oTarget.append(ele);

  $('h1').text(json.Title);
  document.title = json.Title;
  $('.post-attrs').html('<span>' + json.Date + '</span><span><a href="article_list.html?lib="' + json.src + '>' + json.src + '</a></span>');
  $('article-tags').html('')
  for (var i = 0; i < json.tag.length; i++) {
    var ele = $('<li><a href="' + json.tag[i].href + '">' + json.tag[i].name + '</a></li>');
    $('.article-tags').append(ele);
  }
  $('.article-metal a').html('点赞(' + json.meta.zan + ')');
  $('.article-metal .m1').html('浏览(' + json.meta.browsing + ')');
  $('.article-metal .m2').html('评论(' + json.meta.comments + ')');
  $('.article-body').html(json.content);
}

// 中文目录名称转换为对应网址
function findListUrl(str) {
  var url = 'article_list.html?url=';
  switch (str) {
    case '新闻':
      return url + 'news1';
    case '资讯':
      return url + 'news2';
    case '动态':
      return url + 'news3';

    case '活动':
      return url + 'act1';
    case '专栏':
      return url + 'act2';
    case '公益':
      return url + 'act3';

    case '科技':
      return url + 'tech1';
    case '系统':
      return url + 'tech2';
    case '硬件':
      return url + 'tech3';

    case '资源':
      return url + 'res1';
    case '视频':
      return url + 'res2';
    case '讲座':
      return url + 'res3';

    case '图片展示区':
      return url + 'pic1';
    case '链接区':
      return url + 'link1';

    default:
      return 'index.html';
  }

}

// 调取文章 ?ID=
// 调取目录 ?url=

// 图片列表
$(function() {
  if (!$('.imgindex-body')) return false;
  var oParent = $('.imgindex-body');

  var dev = true;
  if (dev) {
    // 开发环境
    $.ajax({
      url: 'virtualdatas/imgindex.json',
      dataType: 'json',
      success: function(json) {
        // console.log(json);
        for (var i = 0; i < json.length; i++) {
          var ele = $('<div class="imgs-list"><a href="imgdisplay.html?imgid=' + json[i].id + '"><h2>' + json[i].title + '</h2><div class="imgindex-trumbs"><div class="img-trumb"><img src="' + json[i].imgsSrc[0] + '" alt="略缩图1"></div><div class="img-trumb"><img src="' + json[i].imgsSrc[1] + '" alt="略缩图2"></div><div class="img-trumb"><img src="' + json[i].imgsSrc[2] + '" alt="略缩图3"></div></div></a></div>');

          oParent.append(ele);
        }

        // 图片排版
        $('.img-trumb img').each(function(index) {
          var height = $(this).height();
          $(this).css({
            'margin-top': -height / 2
          });
          $(this).load(function() {
            var height = $(this).height();
            $(this).css({
              'margin-top': -height / 2
            });

          });
        });
        $('.img-trumb').each(function(index) {
          if ((index - 1) % 3 == 0) {
            $(this).css({
              'margin': '0 38px'
            });
          }
        });
      },
      error: function(err) {
        console.log(err);
      }
    })
  } else {
    // 正式环境
  }
});

// 图片详情
$(function() {
  if (window.location.href.indexOf('imgdisplay') != -1) {
    var articleID = window.location.href.split('?')[1].split('&')[0].split('=')[1];
    console.log(articleID);
    reqImgDetail(articleID);
  }
});

// 请求图片详情
function reqImgDetail(id) {
  var dev = true;
  if (dev) {
    // 开发环境
    $.ajax({
      url: 'virtualdatas/imgdetail.json',
      dataType: 'json',
      success: function(json) {
        // console.log(json);

        var titleWrap = $('h1');
        var postAttrs = $('.post-attrs');
        // 插入数据
        titleWrap.text(json.Title);
        document.title = json.Title;
        postAttrs.append($('<span>' + json.Date + '</span><span>来源: <a href="javascript:;">' + json.src + '</a></span>'))

        var datas = json.imgs;
        // console.log(datas);
        // 图片切换函数
        // 选取dom
        var imgSwitch = document.querySelector('.imgswitch');
        var btnPre = document.querySelector('.imgswitch .pre');
        var btnNext = document.querySelector('.imgswitch .next');
        var imgScan = document.querySelector('.imgswitch .imgscan');
        var btnImg = document.querySelector('.imgswitch .curimg');
        var curImg = document.querySelector('.imgswitch .curimg .imgdisplay');
        var oLoading = document.querySelector('.imgswitch .imgloading');

        var pageTxt = document.querySelector('.imgswitch .page');
        var desTxt = document.querySelector('.imgswitch .des');

        loadPic(0);
        var cur = 0;

        // 前一张图片
        btnPre.onclick = function() {
          if (cur > 0) {
            cur--;
          } else {
            cur = datas.length - 1;
          }
          loadPic(cur);
        };

        // 后一张图片
        btnNext.onclick = function() {
          if (cur < datas.length - 1) {
            cur++;
          } else {
            cur = 0;
          }
          loadPic(cur);
        };

        function loadPic(index) {
          // 加载动画
          oLoading.style.display = 'block';
          btnImg.style.visibility = 'hidden';
          curImg.onload = function() {
            // 初始化
            btnImg.style.left = '70px';
            curImg.style.width = 'auto';
            // 相框图片宽度
            var frameWidth = imgScan.offsetWidth - 140;
            var imgWidth = curImg.offsetWidth;

            var imgHeight = curImg.offsetHeight;
            // console.log('图片规格：', imgWidth);
            // console.log('图片高度:', imgHeight);
            // console.log('相框规格:', frameWidth);
            if (imgWidth >= frameWidth) {
              curImg.style.width = frameWidth + 'px';
            } else {
              btnImg.style.left = (frameWidth - imgWidth) / 2 + 70 + 'px';
            }
            imgScan.style.height = curImg.offsetHeight + 'px';
            // 页面描述
            pageTxt.innerHTML = (index + 1) + ' / ' + datas.length;
            desTxt.innerHTML = datas[index].des;

            // 加载动画
            oLoading.style.display = 'none';
            btnImg.style.visibility = 'visible';
          }

          curImg.src = datas[index].imgSrc;
          btnImg.href = datas[index].imgSrc;
        }


      },
      error: function(err) {

      }
    })
  } else {
    // 正式环境
  }
}
